using Microsoft.AspNetCore.Builder;
using Elasticsearch.Net;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using MT.Enterprise.Utils.Extensions;
using Newtonsoft.Json;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.Contract;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.ElectronicSign;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Platform.Contract;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.BPMReportPlatform.SF.Dto;
using NP.Enterprise.Utils.HanaOdbc;
using NP.Enterprise.Utils.Http;
using RestSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Contract.Dtos.ContractEnum;
using static NP.BPMReportPlatform.SF.Dto.SFDto;
using NP.BPMReportPlatform.Leave.Dto;
using NPOI.HSSF.Record.Chart;
using System.Threading;

namespace NP.BPMReportPlatform.SF
{
    /// <summary>
    /// SF同步接口
    /// </summary>
    public class SFSyncJob : BpmReportPlatformRecurringJob, ISFSyncJob
    {
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly string _sourceSystem = "BPMNEW";
        private readonly string _projectKey, _projectSecret, _signature;
        private readonly string _esbSFGetUrl;
        private readonly string _esbSFPushUrl;
        private readonly string _eSignUrl;
        private readonly IHanaOdbcAppService _hanaAppService;
        private readonly ICommonService _commonService;
        private readonly bool _isProduct;

        public SFSyncJob(ISqlSugarAppService sqlSugarAppService,
            INPRestHttpHelper httpClient, IConfiguration configuration,
            IHanaOdbcAppService hanaAppService, ICommonService commonService)
        {
            _nPRestHttp = httpClient;
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _esbSFGetUrl = configuration["Nippon:ESB:SYQ_ESB_SAPSF_GET_API"];
            _esbSFPushUrl = configuration["Nippon:ESB:SYQ_ESB_SAPSF_API"];
            _hanaAppService = hanaAppService;
            _commonService = commonService;
            _eSignUrl = configuration["Nippon:ESign:Url"];
            _projectKey = configuration["Nippon:ESign:Key"];
            _projectSecret = configuration["Nippon:ESign:Secret"];
            _signature = SHA256Encrypt(_projectKey + _projectSecret, _projectSecret);
            _isProduct = configuration["NeedSendEmail"] == "true";
        }

        /// <summary>
        /// 根据员工工号获取审批信息
        /// </summary>
        /// <param name="workNumber">工号</param>
        /// <returns></returns>
        public List<UserFetchDto> GetCommonRoleUser(string workNumber)
        {
            List<UserFetchDto> result = new List<UserFetchDto>();
            try
            {
                if (string.IsNullOrEmpty(workNumber))
                {
                    return result;
                }

                var user = _dbPlatform.Queryable<Users>().Where(t => t.WorkNumber == workNumber).First();
                if (user != null)
                {
                    var totalUsers = _dbPlatform.Queryable<Users>().Select(t => new { t.UserId, t.WorkNumber, t.UserName }).ToList();
                    var fullpathcodes = user.FullPathCode.Split("_");
                    var commonroles = _dbPlatform.Queryable<CommonRole>().Where(t => !string.IsNullOrWhiteSpace(t.RoleCode) && t.RoleType == "0").ToList();
                    var commonroleusers = _dbPlatform.Queryable<CommonRoleUserRelation>().Where(t => SqlFunc.ContainsArray(fullpathcodes, t.OrgCode)).ToList();
                    string company = string.Empty;

                    var director = _dbPlatform.Queryable<UserExtension>().Where(t => t.Sapemployeeid == workNumber).First();

                    // 手动增加组织归属
                    var orgtypes = _dbPlatform.Queryable<SFDeptLeaderEntity>().Where(t => fullpathcodes.Contains(t.DeptCode) && !string.IsNullOrEmpty(t.DeptCategory)).ToList();

                    string name = string.Empty;
                    if (orgtypes != null && orgtypes.Count() > 0)
                    {
                        for (int i = fullpathcodes.Length - 1; i >= 0; i--)
                        {
                            var orgtype = orgtypes.FirstOrDefault(t => t.DeptCode == fullpathcodes[i]);
                            if (orgtype != null && !orgtype.DeptCategory.IsNullOrWhiteSpace())
                            {
                                name = EnumExtension.GetDescription(typeof(OrgTypeEnum), Int32.Parse(orgtype.DeptCategory));
                                // 手动加入直接主管，隔级主管
                                result.Add(new UserFetchDto
                                {
                                    RoleCode = "cust_organizationCategory",
                                    UserName = name,
                                    WorkNumber = orgtype?.DeptCategory,
                                });
                                break;
                            }
                        }
                    }
                    else
                    {
                        // 手动加入直接主管，隔级主管
                        result.Add(new UserFetchDto
                        {
                            RoleCode = "cust_organizationCategory",
                            UserName = string.Empty,
                            WorkNumber = string.Empty,
                        });
                    }

                    // 手动加入职级
                    result.Add(new UserFetchDto
                    {
                        RoleCode = "Posnc",
                        UserName = director?.Poste,
                        WorkNumber = director?.Posnc,
                    });

                    // 手动加入直接主管，隔级主管
                    result.Add(new UserFetchDto
                    {
                        RoleCode = "Director",
                        UserName = director?.Bossname,
                        WorkNumber = director?.Bossemployeeid,
                    });

                    var bossemployeeid = director?.Bossemployeeid;
                    // 根据员工工号找到隔级主管工号
                    var superBossemployeeid = _dbPlatform.Queryable<SFPositionUserRelEntity, SFPositions, SFPositionUserRelEntity, SFPositions, SFPositionUserRelEntity>((a, b, c, d, e) =>
                    new JoinQueryInfos(JoinType.Inner, a.PositionCode == b.PositionCode, JoinType.Inner, b.ParentPositionCode == c.PositionCode,
                    JoinType.Inner, c.PositionCode == d.PositionCode, JoinType.Inner, d.ParentPositionCode == e.PositionCode))
                        .Where((a, b, c, d, e) => a.UserId == workNumber)
                        .Select((a, b, c, d, e) => e.UserId)
                        .First();

                    var SuperDirector = _dbPlatform.Queryable<UserExtension>().Where(t => t.Sapemployeeid == superBossemployeeid && !string.IsNullOrEmpty(t.Sapemployeeid)).First();

                    result.Add(new UserFetchDto
                    {
                        RoleCode = "SuperDirector",
                        UserName = SuperDirector?.Name,
                        WorkNumber = SuperDirector?.Sapemployeeid,
                    });

                    if (SuperDirector != null)
                    {
                        // 隔级主管上级
                        var DirectorOfSuperDirector = _dbPlatform.Queryable<UserExtension>().Where(t => t.Sapemployeeid == SuperDirector.Bossemployeeid && !string.IsNullOrEmpty(t.Sapemployeeid)).First();

                        result.Add(new UserFetchDto
                        {
                            RoleCode = "DirectorOfSuperDirector",
                            UserName = DirectorOfSuperDirector?.Name,
                            WorkNumber = DirectorOfSuperDirector?.Sapemployeeid,
                        });
                    }

                    commonroles.ForEach(commonrole =>
                    {
                        for (int i = fullpathcodes.Length - 1; i >= 0; i--)
                        {
                            company = fullpathcodes[i];
                            if (commonroleusers.Where(t => t.OrgCode == company && t.RoleId == commonrole.RoleId).Count() > 0)
                            {
                                commonroleusers.Where(t => t.OrgCode == company && t.RoleId == commonrole.RoleId).ToList().ForEach(q =>
                                {
                                    string name = q.UserName;
                                    var user = totalUsers.Where(t => t.UserId == q.UserId).FirstOrDefault();
                                    if (user != null && !string.IsNullOrEmpty(user.UserName))
                                    {
                                        name = user.UserName;
                                    }

                                    result.Add(new UserFetchDto
                                    {
                                        RoleCode = commonrole.RoleCode,
                                        UserName = user.UserName,
                                        WorkNumber = user.WorkNumber,
                                    });
                                });
                                break;
                            }
                        }

                        // 如果没有，给个空，告诉别人有这个角色
                        if (result.Where(t => t.RoleCode == commonrole.RoleCode).Count() == 0)
                        {
                            result.Add(new UserFetchDto
                            {
                                RoleCode = commonrole.RoleCode,
                                UserName = string.Empty,
                                WorkNumber = string.Empty,
                            });
                        }
                    });
                }
            }
            catch (Exception)
            {
            }

            return result;
        }

        public async Task SyncHanaData()
        {
            await SyncHanaUserAsync(string.Empty); // 同步员工基本扩展信息
            await SyncCorporate(); // 同步法人公司
            await SyncUserPref(); // 同步员工绩效
            await SyncContractAddress(); // 同步合同地址
        }

        /// <summary>
        /// 通用接口：同步DOA审批角色相关数据
        /// </summary>
        /// <returns></returns>
        public async Task<string> SyncSFData()
        {
            string result = string.Empty;
            result = await SyncGetPositionRole(); // 岗位
            result += await SyncGetManagerRole(); // 直接主管，隔级主管
            result += await SyncGetPartManagerRole(); // 兼岗接口
            result += await SyncGetHRBPRole(); // 通用角色
            result += await SyncGetDeptLeaderRole(); // 部门负责人
            result += await SyncGetOtherRole(); // 获取薪资员、行政、员工关系角色
            return result;
        }

        /// <summary>
        /// 发送-未签合同提醒
        /// </summary>
        /// <returns></returns>
        public async Task SyncSendEmail()
        {
            try
            {
                // 给HRBP发的
                // 合同到期提醒
                DateTime date = DateTime.Now.AddDays(60);
                DateTime startdate = new DateTime(date.Year, date.Month, date.Day);
                DateTime enddate = startdate.AddDays(1).AddMinutes(-1);

                DateTime date1 = DateTime.Now.AddDays(45);
                DateTime startdate1 = new DateTime(date1.Year, date1.Month, date1.Day);
                DateTime enddate1 = startdate1.AddDays(1).AddMinutes(-1);

                List<string> allDeptCodes = new List<string>();

                // 找到第45天和第60天的合同
                var allDeptFullPathCodes = _dbPlatform.Queryable<UserContractEntity, Users>((p, b) => p.WorkNumber == b.WorkNumber)
                               .Where((p, b) => (p.ContractEndDate >= startdate && p.ContractEndDate <= enddate)
                               || (p.ContractEndDate >= startdate1 && p.ContractEndDate <= enddate1))
                               .Where((p, b) => p.ContractStatus == (int)ContractEnum.ContractStatusEnum.履行中)
                               .Select((p, b) => b.FullPathCode).Distinct().ToList();

                if (allDeptFullPathCodes != null && allDeptFullPathCodes.Count() > 0)
                {
                    allDeptFullPathCodes.ForEach(t =>
                    {
                        allDeptCodes.AddRange(t.Split("_").ToList());
                    });
                }
                allDeptCodes = allDeptCodes.Distinct().ToList();

                // 找到这些人对应的HRBP负责人(反向查找难哦)
                var allworkNumbers = _dbPlatform.Queryable<SFPositionUserRelEntity, SFApproverEntity>((a, b) => a.PositionCode == b.PositionCode)
                    .Where((a, b) => allDeptCodes.Contains(b.DeptCode) && !string.IsNullOrEmpty(b.DeptCode)
                    && b.RoleCode == "HRBPPermission").Select((a, b) => a.UserId).Distinct().ToList();

                // 给每个人发邮件
                foreach (var item in allworkNumbers)
                {
                    await _commonService.SendEmail(ContractEmailTypeEnum.合同到期提醒, string.Empty,
                    item, string.Empty);
                }

                // 职级20及以上员工合同到期提醒
                await PosncContractSendEmail();

                // 给发起人发的
                // 未签主体变更协议提醒
                var allUser = _dbPlatform.Queryable<UserContractTripartiteAgreementEntity>()
                               .Where(p => p.ChangeStatus == (int)ContractEnum.ContractChangeStatusEnum.签署中)
                                .Select(p => p.CreateWorkNumber).Distinct().ToList();

                foreach (var item in allUser)
                {
                    await _commonService.SendEmail(ContractEmailTypeEnum.未签主体变更协议提醒, string.Empty,
                   item, string.Empty);
                }

                // 给发起人
                // 未签合同提醒
                var allUser2 = _dbPlatform.Queryable<UserContractEntity>()
                               .Where(p => p.ContractStatus == (int)ContractEnum.ContractStatusEnum.签署中)
                               .Select(p => p.CreateUserWorkNumber).Distinct().ToList();

                foreach (var item in allUser2)
                {
                    await _commonService.SendEmail(ContractEmailTypeEnum.未签合同提醒, string.Empty,
                    item, string.Empty); // 未签合同提醒
                }

                // 给员工关系
                // 提醒新员工合同还未发起
                var allUser3 = _dbPlatform.Queryable<SFOtherApproverEntity>()
                              .Where(p => p.RelationshipType == "1938")
                              .Select(p => p.RelUserId).Distinct().ToList();

                foreach (var item in allUser3)
                {
                    await _commonService.SendEmail(ContractEmailTypeEnum.未发起合同提醒, string.Empty,
                    item, string.Empty);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 发送职级20以上的员工合同到期提醒邮件
        /// </summary>
        /// <returns></returns>
        public async Task PosncContractSendEmail()
        {
            try
            {
                var allworkNumbers = _dbPlatform.Queryable<Dictionaries>().Where(x => x.TypeCode == "PosncContractEmailConfig"
                    && x.Status == 1).Select(x => x.Value).ToList();

                // 给每个人发邮件
                foreach (var item in allworkNumbers)
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        await _commonService.SendEmail(ContractEmailTypeEnum.职级20及以上员工合同到期提醒, string.Empty, item, string.Empty);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 同步甲方公司
        /// </summary>
        /// <returns></returns>
        public async Task<string> SyncCorporate()
        {
            string msgResult = "---- SyncCorporate  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetCompanyInfo_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<CorporateEntity> needAdds = new List<CorporateEntity>();
                var totalCorporate = _dbPlatform.Queryable<CorporateEntity>().ToList();
                totalCorporate.ForEach(t => t.Status = 0);
                var totalCorporateCodes = totalCorporate.Select(t => t.CorporateCode).ToList();
                var accountid = _dbPlatform.Queryable<UserExtensionSecondEntity>().Where(t => t.UserName == "盛俐敏").First()?.AccountId;
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""externalCode,name_zh_CN,status,cust_unifiedSocialCreditCode,cust_contactNumber,cust_zipCode,cust_registeredAddress,cust_legalRepresentative""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFCorporateResponse.SFCorporate>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        CorporateEntity corporate = null;
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            corporate = totalCorporate.FirstOrDefault(t => t.CorporateCode == item.externalCode);
                            if (corporate != null)
                            {
                                corporate.CorporateName = item.name_zh_CN;
                                corporate.CorporateAddress = item.cust_registeredAddress;
                                corporate.CorporatePhone = item.cust_contactNumber;
                                corporate.CorporatePostCode = item.cust_zipCode;
                                corporate.CreditCode = item.cust_unifiedSocialCreditCode;
                                corporate.Status = item.status == "A" ? 1 : 0;
                                corporate.LegalPerson = item.cust_legalRepresentative;
                                if (corporate.AccountId.IsNullOrEmpty())
                                {
                                    corporate.AccountId = accountid;
                                    corporate.AccountUserName = "盛俐敏";
                                }
                            }
                            else if (!item.externalCode.IsNullOrEmpty())
                            {
                                needAdds.Add(new CorporateEntity()
                                {
                                    CorporateCode = item.externalCode,
                                    CorporateName = item.name_zh_CN,
                                    CorporateAddress = item.cust_registeredAddress,
                                    CorporatePhone = item.cust_contactNumber,
                                    CorporatePostCode = item.cust_zipCode,
                                    Status = item.status == "A" ? 1 : 0,
                                    AccountId = accountid,
                                    AccountUserName = "盛俐敏",
                                    LegalPerson = item.cust_legalRepresentative
                                });
                            }
                        }
                    }
                }
                _dbPlatform.Updateable(totalCorporate).ExecuteCommand();
                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncCorporate  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 同步员工绩效数据
        /// </summary>
        /// <returns></returns>
        public async Task<string> SyncUserPref()
        {
            string msgResult = "---- SyncPref  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetPmgInfo_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFUserPrefEntity> needAdds = new List<SFUserPrefEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""externalCode,effectiveStartDate,cust_toPerformanceInfo/externalName,cust_toPerformanceInfo/cust_name,cust_toPerformanceInfo/cust_year,cust_toPerformanceInfo/cust_result"",""$expand"":""cust_toPerformanceInfo""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFUserPerfResponse.SFUserPerf>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        if (result?.d?.results.Count() > 0)
                        {
                            foreach (var item in result?.d?.results)
                            {
                                if (item.cust_toPerformanceInfo != null && item.cust_toPerformanceInfo.results != null && item.cust_toPerformanceInfo.results.Count() > 0)
                                {
                                    needAdds.AddRange(item.cust_toPerformanceInfo.results.Select(t => new SFUserPrefEntity()
                                    {
                                        Id = Guid.NewGuid().ToString(),
                                        CustName = t.cust_name,
                                        CustResult = t.cust_result,
                                        CustYear = t.cust_year ?? 0,
                                        ExternalName = t.externalName,
                                        WorkNumber = item.externalCode
                                    }).ToList());
                                }

                            }
                        }

                    }
                }
                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFUserPrefEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncPref  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 同步合同地址
        /// </summary>
        /// <returns></returns>
        public async Task<string> SyncContractAddress()
        {
            string msgResult = "---- SyncContractAddressPref  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetContractAddress_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<CityAreaEntity> needAdds = new List<CityAreaEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""filter"":""id%20eq%20%27contractLocation%27%20and%20values/status%20eq%20%27A%27"",""$select"":""id,parentPickList,values/parentPickListValue,values/externalCode,values/label_zh_CN,values/optionId,values/status"",""$expand"":""values""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFContractAddressResponse.SFContractAddress>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        var contractAddress = result?.d?.results.Where(t => t.id == "contractLocation").FirstOrDefault();
                        // 数据处理
                        if (contractAddress != null && contractAddress.values != null
                            && contractAddress.values.results != null && contractAddress.values.results.Count() > 0)
                        {
                            needAdds.AddRange(contractAddress?.values?.results.Where(t => t.status == "A").Select(t => new CityAreaEntity()
                            {
                                Code = t.externalCode,
                                IsEnd = true,
                                Name = t.label_zh_CN,
                                ParentCode = string.Empty,
                            }).ToList());
                        }
                    }
                }
                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<CityAreaEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncContractAddressPref  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 回写合同信息
        /// </summary>
        /// <param name="contractCode">合同编号</param>
        public string PushContractToSF(string contractCode)
        {
            string result = string.Empty;
            var contract = _dbPlatform.Queryable<UserContractEntity>().Where(t => t.ContractCode == contractCode).First();

            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_PostContractInfo_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                if (contract == null)
                {
                    return "找不到指定合同：" + contractCode;
                }

                string downloadUrl = GetESDownloadUrl(contract.SignFlowId);

                // 转换数据，SF就是大爷
                var changeData = ChangeDateForSF(contract);

                // 数据整理
                var requestBody = new
                {
                    url = new { format = "json", purgeType = "record" },
                    body = new
                    {
                        __metadata = new
                        {
                            type = "SFOData.cust_contract",
                            uri = $"cust_contract"
                        },
                        externalCode = contract.WorkNumber,
                        effectiveStartDate = ToSFStr(contract.ContractStartDate.Value, true),
                        cust_toContractInfo = new
                        {
                            results = new List<object>()
                            {
                                new
                               {
                                    __metadata = new { type = "SFOData.cust_contractInfo",
                                        uri=$"cust_contractInfo" },
                                    cust_contract_externalCode = contract.WorkNumber,
                                    cust_contract_effectiveStartDate = ToSFStr(contract.ContractStartDate.Value,true),
                                    cust_code = contract.ContractCode,
                                    cust_contractType = changeData["cust_contractType"],
                                    cust_timeType = changeData["cust_timeType"],
                                    cust_startDate = ToSFStr(contract.ContractStartDate.Value,true),
                                    cust_endDate = ToSFStr(contract.ContractEndDate.Value,true),
                                    cust_signTime = ToSFStr(contract.SignDate.Value,true),
                                    cust_state = changeData["cust_state"],
                                    cust_location =  _isProduct ? changeData["cust_location"]:"999007", // 999007 上海
                                    cust_ifPromotion = changeData["cust_ifPromotion"],
                                    cust_IU = changeData["cust_IU"],
                                    cust_ifElectronicSignature = changeData["cust_ifElectronicSignature"],
                                    cust_address = contract.ContactAddress,
                                    cust_cardCode = contract.CardNum,
                                    cust_cardType = contract.CardName,
                                    cust_firstPartyPeople = contract.CreateUserWorkNumber, // 传经办人工号
                                    cust_firstPartyName = contract.CorporateCode, // 法人公司代码
                                    cust_firstPartyPhone = contract.CorporatePhone,
                                    cust_firstPartyZipCode = contract.CorporatePostCode,
                                    cust_hjdz = contract.CardAddress,
                                    cust_hkxz = contract.CategoryType,
                                    cust_timeAttribute = contract.TimeSheetType,
                                    cust_signType = changeData["cust_signType"],
                                    cust_phone = contract.MobilePhone,
                                    cust_firstPartyCompanyCode = contract.CorporateCode,
                                    cust_firstPartyAddress = contract.CorporateAddress,
                                    cust_nationalId = contract.CardNum,
                                    cust_zipCode = contract.PostCode,
                                    cust_promotionStartDate = ToSFStr(contract.SYQStartDate ?? DateTime.Now,true),
                                    cust_promotionEndDate = ToSFStr(contract.SYQEndDate ?? DateTime.Now,true),
                                    cust_promotionMonth = contract.SYQMonth ?? 0,
                                    cust_link = string.IsNullOrEmpty(downloadUrl)?"待传附件":downloadUrl
                                }
                            }
                        }

                    },
                };
                var requeststr1 = JsonConvert.SerializeObject(requestBody).Replace("format", "$format");

                var resDataStr = _nPRestHttp.ESBPostAsync(_esbSFPushUrl, requeststr1, dic).Result;
                var resData = JsonConvert.DeserializeObject<SFContractPushResponse.SFContractPush>(resDataStr);

                // 数据处理
                if (resData?.d != null && resData?.d.Count > 0)
                {
                    contract.SFPushDate = DateTime.Now;
                    contract.SFPushStatus = resData.d[0].status == "OK" ? 1 : -1;
                    contract.SFPushErrorMsg = resData.d[0].message;
                };
            }
            catch (Exception ex)
            {
                result = ex.Message;
                contract.SFPushDate = DateTime.Now;
                contract.SFPushStatus = -1;
                contract.SFPushErrorMsg = ex.Message;
            }
            finally
            {
                if (contract != null)
                {
                    _dbPlatform.Updateable(contract).UpdateColumns(t => new { t.SFPushDate, t.SFPushStatus, t.SFPushErrorMsg }).ExecuteCommand();
                }
            }

            return result;
        }

        /// <summary>
        /// 回写合同主体变更信息
        /// </summary>
        /// <param name="contractCode">合同编号</param>
        public async Task<string> PushContractChangeToSF(string contractChangeCode)
        {
            string result = string.Empty;
            var contract = _dbPlatform.Queryable<UserContractTripartiteAgreementEntity>().Where(t => t.ChangeContractCode == contractChangeCode).First();

            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_PostAgrInfo_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                if (contract == null)
                {
                    return "找不到指定合同协议变更：" + contractChangeCode;
                }

                string downloadUrl = GetESDownloadUrl(contract.SignFlowId);

                // 数据整理
                var requestBody = new
                {
                    url = new { format = "json", purgeType = "record" },
                    body = new
                    {
                        __metadata = new { type = "SFOData.cust_contractChange", uri = "cust_contractChange" },
                        externalCode = contract.PartyBCode,
                        effectiveStartDate = ToSFStr(contract.ContractChangeDate.Value, true),
                        cust_toContractChange = new
                        {
                            results = new List<object>()
                            {
                                new {
                                    __metadata = new { type = "SFOData.cust_contractChangeDetails", uri = "cust_contractChangeDetails" },
                                    cust_contractChange_externalCode = contract.PartyBCode,
                                    cust_contractChange_effectiveStartDate = ToSFStr(contract.ContractChangeDate.Value,true),
                                    cust_role1 = contract.PartyACode,
                                    cust_address1 = contract.PartyAAddress,
                                    cust_representative1 = contract.PartyALegalPerson,
                                    cust_role2 = contract.PartyBCode,
                                    cust_address2 = contract.PartyBAddress,
                                    cust_ID = contract.PartyBCardNo,
                                    cust_role3 = contract.PartyCCode,
                                    cust_address3 = contract.PartyCAddress,
                                    cust_representative3 = contract.PartyCLegalPerson,
                                    cust_code = contract.ChangeContractCode,
                                    cust_orignalCode = contract.OriginalContractCode,
                                    cust_changeDate = ToSFStr(contract.ContractChangeDate.Value,true),
                                    cust_orignalStartDate = ToSFStr(contract.OriginalContractStartDate.Value,true),
                                    cust_orignalEndDate = ToSFStr(contract.OriginalContractEndDate.Value,true),
                                    cust_ifElectronicSignature = contract.SignFlowId.IsNullOrEmpty() ? "0" : "1",
                                    cust_link = string.IsNullOrEmpty(downloadUrl)?"待传附件":downloadUrl
                                }
                            }
                        }
                    },
                };
                var requeststr1 = JsonConvert.SerializeObject(requestBody).Replace("format", "$format");

                var resData = _nPRestHttp.ESBPostAsync<SFContractPushResponse.SFContractPush>(_esbSFPushUrl, requeststr1, dic).Result;

                // 数据处理
                if (resData?.d != null && resData?.d.Count > 0)
                {
                    contract.SFPushDate = DateTime.Now;
                    contract.SFPushStatus = resData.d[0].status == "OK" ? 1 : -1;
                    contract.SFPushErrorMsg = resData.d[0].message;
                };
            }
            catch (Exception ex)
            {
                result = ex.Message;
                contract.SFPushDate = DateTime.Now;
                contract.SFPushStatus = -1;
                contract.SFPushErrorMsg = ex.Message;
            }
            finally
            {
                if (contract != null)
                {
                    _dbPlatform.Updateable(contract).UpdateColumns(t => new { t.SFPushDate, t.SFPushStatus, t.SFPushErrorMsg }).ExecuteCommand();
                }
            }

            return result;
        }

        /// <summary>
        /// 更新合同基础数据，适配给SF
        /// </summary>
        /// <param name="contract"></param>
        private Dictionary<string, string> ChangeDateForSF(UserContractEntity contract)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            result.Add("cust_contractType", string.Empty); // 合同类型
            result.Add("cust_timeType", string.Empty); // 合同期限类型
            result.Add("cust_signType", string.Empty);
            result.Add("cust_state", "2"); // 合同状态：默认只给履行中的
            result.Add("cust_location", contract.WorkAddress);
            result.Add("cust_ifPromotion", contract.HasSYQ ? "1" : "0"); // 是否有试用期
            result.Add("cust_IU", string.Empty);
            result.Add("cust_ifElectronicSignature", contract.SignFlowId.IsNullOrEmpty() ? "0" : "1"); //是否发起电子签
            result.Add("cust_cardType", string.Empty);


            // 合同类型 劳动合同/聘用合同/劳务合同/实习合同/返聘合同
            var cust_contractType = contract.ContractTypeCode == "LD" ? "0" :
                                        contract.ContractTypeCode == "PY" ? "1" :
                                        contract.ContractTypeCode == "LW" ? "2" :
                                        contract.ContractTypeCode == "SX" ? "3" :
                                        contract.ContractTypeCode == "FP" ? "4" : "";

            result["cust_contractType"] = cust_contractType;

            // 合同期限类型
            var cust_timeType = (contract.ContractTypeCode == "LD" && contract.ContractDeadLineCode == (int)ContractEnum.ContractTypeEnum.短期合同) ? "02" :
                                            (contract.ContractTypeCode == "LD" && contract.ContractDeadLineCode == (int)ContractEnum.ContractTypeEnum.中长期合同) ? "01" :
                                            (contract.ContractTypeCode == "LD" && contract.ContractDeadLineCode == (int)ContractEnum.ContractTypeEnum.无固定期限) ? "03" :
                                            contract.ContractTypeCode == "PY" ? "10" :
                                            contract.ContractTypeCode == "LW" ? "20" :
                                            contract.ContractTypeCode == "SX" ? "30" :
                                            contract.ContractTypeCode == "FP" ? "40" : "";
            result["cust_timeType"] = cust_timeType;

            // 签订类型 01 签订 02 续签 03 变更
            result["cust_signType"] = contract.ContractCount == 1 ? "01" : "02";

            // 是否IU
            var userareas = _dbPlatform.Queryable<Dictionaries>()
                 .Where(t => t.TypeCode == "HR_IU").Select(t => t.Value).ToList();
            var userExtension = _dbPlatform.Queryable<UserExtension>()
                   .Where(a => a.Sapemployeeid == contract.WorkNumber && (userareas.Contains(a.Objid_1) || userareas.Contains(a.Objid_2) || userareas.Contains(a.Objid_3)))
                   .First();
            result["cust_IU"] = userExtension == null ? "0" : "1";
            return result;
        }

        /// <summary>
        /// 同步Hana用户信息(身份证)
        /// </summary>
        /// <returns></returns>
        public async Task<object> SyncHanaUserAsync(string workNumber)
        {
            try
            {
                var sql = $@"SELECT EMPCODE ,EMPNAM ,IDTYPE ,IDCARD  FROM _SYS_BIC.""com.hr.LL/CA_EMP_IDCARD""";
                var rst = (await _hanaAppService.GetListAsync<HanaDto.CardDto>(sql)).Where(t => !string.IsNullOrEmpty(t.IDCARD)).ToList();
                if (rst != null && rst.Count() > 0)
                {
                    var totalUserExtensions = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                    var totalUsers = _dbPlatform.Queryable<Users>().Where(t => t.Status == 1).Select(t => new { t.UserId, t.WorkNumber, t.UserName }).ToList();
                    var needAdds = new List<UserExtensionSecondEntity>();
                    foreach (var item in rst)
                    {
                        var userExtension = totalUserExtensions.FirstOrDefault(t => t.WorkNumber == item.EMPCODE);
                        if (userExtension == null)
                        {
                            var user = totalUsers.FirstOrDefault(t => t.WorkNumber == item.EMPCODE);
                            if (user != null)
                            {
                                // 重复数据
                                if (needAdds.Select(t => t.WorkNumber).Contains(item.EMPCODE))
                                {
                                    if (item.IDCARD == "01")
                                    {
                                        var neeadd = needAdds.FirstOrDefault(t => t.WorkNumber == item.EMPCODE);
                                        neeadd.CardTypeCode = item.IDTYPE;
                                        neeadd.CardNum = item.IDCARD;
                                        neeadd.CardTypeName = "身份证";
                                    }
                                }
                                else
                                {
                                    needAdds.Add(new UserExtensionSecondEntity()
                                    {
                                        UserId = user.UserId,
                                        WorkNumber = user.WorkNumber,
                                        UserName = user.UserName,
                                        CardTypeCode = item.IDTYPE,
                                        CardNum = item.IDCARD,
                                        CardTypeName =
                                   item.IDTYPE == "01" ? "身份证"
                                   : item.IDTYPE == "02" ? "护照"
                                   : item.IDTYPE == "03" ? "港澳居民来往内地通行证"
                                   : item.IDTYPE == "04" ? "台湾居民来往大陆通行证"
                                   : item.IDTYPE == "05" ? "原籍国ID"
                                   : item.IDTYPE == "V1" ? "签证 1"
                                   : item.IDTYPE == "V2" ? "签证 2"
                                   : item.IDTYPE == "V3" ? "签证 3"
                                   : item.IDTYPE == "V4" ? "港澳通行证" : item.IDTYPE
                                    });
                                }
                            }
                        }
                        else
                        {
                            userExtension.CardTypeCode = item.IDTYPE;
                            userExtension.CardNum = item.IDCARD;
                            userExtension.CardTypeName =
                            item.IDTYPE == "01" ? "身份证"
                            : item.IDTYPE == "02" ? "护照"
                            : item.IDTYPE == "03" ? "港澳居民来往内地通行证"
                            : item.IDTYPE == "04" ? "台湾居民来往大陆通行证"
                            : item.IDTYPE == "05" ? "原籍国ID"
                            : item.IDTYPE == "V1" ? "签证 1"
                            : item.IDTYPE == "V2" ? "签证 2"
                            : item.IDTYPE == "V3" ? "签证 3"
                            : item.IDTYPE == "V4" ? "港澳通行证" : item.IDTYPE;

                            if (rst.Count(t => t.EMPCODE == item.EMPCODE) > 1)
                            {
                                var useitem = rst.Where(t => t.EMPCODE == item.EMPCODE && t.IDTYPE == "01").FirstOrDefault();
                                if (useitem != null)
                                {
                                    userExtension.CardTypeCode = useitem.IDTYPE;
                                    userExtension.CardNum = useitem.IDCARD;
                                    userExtension.CardTypeName = "身份证";
                                }
                            }
                        }
                    }

                    if (needAdds != null && needAdds.Count() > 0)
                    {
                        _dbPlatform.Insertable(needAdds).ExecuteCommand();
                    }

                    if (totalUserExtensions != null)
                    {
                        _dbPlatform.Updateable(totalUserExtensions)
                            .UpdateColumns(t => new { t.CardTypeCode, t.CardNum, t.CardTypeName })
                            .ExecuteCommand();
                    }
                }
            }
            catch (Exception)
            {
                return "false";
            }

            await SyncHanaUserAsync2();
            await SyncHanaUserAsync3();
            await SyncHanaUserAsync4();
            await SyncPostionExpand();
            await SyncUserTimeSheet();

            return "true";
        }

        /// <summary>
        /// 同步Hana用户信息(户口地址)
        /// </summary>
        /// <returns></returns>
        public async Task<object> SyncHanaUserAsync2()
        {
            // Z1 联络地址 Z2:家庭地址 邮编 Z3:户口地址 Z4:工作地址 Z5 参保地址
            var sql = $@"SELECT PERNR ,STRAS ,ORT01 ,STATE ,ANSSA ,PSTLZ ,STATE_TXT  FROM _SYS_BIC.""com.hr.LL/CA_PA0006""";
            var rst = (await _hanaAppService.GetListAsync<HanaDto.AddressDto>(sql));
            if (rst != null && rst.Count() > 0)
            {
                var totalUserExtensions = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                var rsts = new List<HanaDto.AddressDto>();
                var cardAddress = new HanaDto.AddressDto();
                var contactAddress = new HanaDto.AddressDto();
                string cardAddress1 = string.Empty;
                string cardAddress2 = string.Empty;
                string contactAddress1 = string.Empty;
                string contactAddress2 = string.Empty;
                string cardAddressPre = string.Empty;
                string contactAddressPre = string.Empty;
                foreach (var user in totalUserExtensions)
                {
                    rsts = rst.Where(t => t.PERNR == user.WorkNumber).ToList();
                    contactAddress = rsts.FirstOrDefault(t => t.ANSSA == "Z2");
                    cardAddress = rsts.FirstOrDefault(t => t.ANSSA == "Z3");

                    cardAddress1 = cardAddress?.STATE_TXT ?? ""; // 省
                    cardAddress2 = cardAddress?.ORT01 ?? ""; // 市
                    contactAddress1 = contactAddress?.STATE_TXT ?? ""; // 省
                    contactAddress2 = contactAddress?.ORT01 ?? ""; // 市
                    cardAddressPre = cardAddress2.StartsWith(cardAddress1) ? cardAddress2 : (cardAddress1 + cardAddress2);
                    contactAddressPre = contactAddress2.StartsWith(contactAddress1) ? contactAddress2 : (contactAddress1 + contactAddress2);

                    user.CardAddress = cardAddressPre + (cardAddress?.STRAS ?? "");
                    user.ContactAddress = contactAddressPre + (contactAddress?.STRAS ?? "");
                    user.PostCode = rsts.FirstOrDefault(t => t.ANSSA == "Z2")?.PSTLZ;
                    user.WorkAddress = rsts.FirstOrDefault(t => t.ANSSA == "Z4")?.STRAS ?? "";
                    user.ORT01 = rsts.FirstOrDefault(t => t.ANSSA == "Z4")?.ORT01 ?? "";
                }

                if (totalUserExtensions != null)
                {
                    _dbPlatform.Updateable(totalUserExtensions)
                        .UpdateColumns(t => new { t.CardAddress, t.ContactAddress, t.PostCode, t.WorkAddress, t.ORT01 })
                        .ExecuteCommand();
                }
            }
            return rst.Count();
        }

        /// <summary>
        /// 同步Hana用户信息(年龄，户口性质)
        /// </summary>
        /// <returns></returns>
        public async Task<object> SyncHanaUserAsync3()
        {
            var sql = $@"SELECT PERNR ,GBDAT ,ZZHUK ,ZZHUK_TXT FROM _SYS_BIC.""com.hr.LL/CA_EMP_INFO"" WHERE ZZHUK IS NOT NULL AND ZZHUK != ''";
            var rst = (await _hanaAppService.GetListAsync<HanaDto.CategoryTypeDto>(sql));
            if (rst != null && rst.Count() > 0)
            {
                var totalUserExtensions = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                foreach (var userExtension in totalUserExtensions)
                {
                    var user = rst.FirstOrDefault(t => t.PERNR == userExtension.WorkNumber);
                    if (user != null)
                    {
                        userExtension.Age = DateTime.Now.Year - Int32.Parse(user.GBDAT.Substring(0, 4));
                        userExtension.CategoryType = user?.ZZHUK_TXT;
                    }
                }

                if (totalUserExtensions != null)
                {
                    _dbPlatform.Updateable(totalUserExtensions)
                        .UpdateColumns(t => new { t.Age, t.CategoryType })
                        .ExecuteCommand();
                }
            }
            return rst.Count();
        }

        /// <summary>
        /// 同步Hana用户信息(学历,毕业时间，学校, 专业)
        /// </summary>
        /// <returns></returns>
        public async Task<object> SyncHanaUserAsync4()
        {
            var sql = $@"SELECT PERNR ,STEXT ,BEGDA ,ENDDA,INSTI,Z_SPECIAL  FROM  _SYS_BIC.""com.hr.LL/CA_PA0022"" ORDER BY BEGDA ";
            var rst = (await _hanaAppService.GetListAsync<HanaDto.EducationDto>(sql));
            if (rst != null && rst.Count() > 0)
            {
                var totalUserExtensions = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                foreach (var userExtension in totalUserExtensions)
                {
                    var user = rst.LastOrDefault(t => t.PERNR == userExtension.WorkNumber);
                    userExtension.Education = user?.STEXT;
                    if (!string.IsNullOrEmpty(user?.ENDDA))
                    {
                        userExtension.EndDate = DateTime.ParseExact(user?.ENDDA, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                    }
                    userExtension.School = user?.INSTI;
                    userExtension.Special = user?.Z_SPECIAL;
                }

                if (totalUserExtensions != null)
                {
                    _dbPlatform.Updateable(totalUserExtensions)
                        .UpdateColumns(t => new { t.Education, t.EndDate, t.School, t.Special })
                        .ExecuteCommand();
                }
            }
            return rst.Count();
        }

        #region 通用接口：同步DOA审批角色

        /// <summary>
        /// 岗位接口(上下岗位)
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetPositionRole()
        {
            string msgResult = "---- SyncGetPositionRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetPositionRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFPositionEntity> needAdds = new List<SFPositionEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""code,externalName_zh_CN,effectiveStatus,parentPosition/code,parentPosition/externalName_zh_CN,parentPosition/effectiveStatus"",""$expand"":""parentPosition""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFPositionRoleResponse.SFPositionRole>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            if (item.effectiveStatus == "A")
                            {
                                needAdds.Add(new SFPositionEntity()
                                {
                                    Id = Guid.NewGuid().ToString(),
                                    PositionCode = item.code,
                                    PositionName = item.externalName_zh_CN,
                                    ParentPositionCode = item.parentPosition?.code,
                                    ParentPositionName = item.parentPosition?.externalName_zh_CN,
                                });
                            }
                        }
                    }
                }

                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFPositionEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncGetPositionRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 主岗_人员关系接口
        /// 直接主管，隔级主管
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetManagerRole()
        {
            string msgResult = "---- SyncGetManagerRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetManagerRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFPositionUserRelEntity> needAdds = new List<SFPositionUserRelEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$expand"":""positionNav,employmentNav"",""$select"":""userId,managerId,position,emplStatus,positionNav/externalName_zh_CN,employmentNav/personIdExternal"",""$filter"":""emplStatus eq '1189'""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFManageRoleResponse.SFManageRole>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            var userrid = item.employmentNav?.personIdExternal ?? item.userId;
                            needAdds.Add(new SFPositionUserRelEntity()
                            {
                                Id = Guid.NewGuid().ToString(),
                                DataType = 1,
                                ManagerId = item.managerId,
                                PositionCode = item.position,
                                UserId = string.IsNullOrEmpty(userrid) ? "" : userrid.Split('-')[0]
                            });
                        }
                    }
                }
                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFPositionUserRelEntity>().Where(t => t.DataType == 1).ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncGetManagerRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        ///  兼岗_人员关系接口
        /// 直接主管，隔级主管
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetPartManagerRole()
        {
            string msgResult = "---- SyncGetPartManagerRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetJZManagerRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFPositionUserRelEntity> needAdds = new List<SFPositionUserRelEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""externalCode,allSfProcesses/SecondaryAssignments_effectiveStartDate,allSfProcesses/usersSysIdNav/empInfo/jobInfoNav/emplStatus,allSfProcesses/usersSysIdNav/empInfo/jobInfoNav/position"",""$expand"":""allSfProcesses,allSfProcesses/usersSysIdNav,allSfProcesses/usersSysIdNav/empInfo,allSfProcesses/usersSysIdNav/empInfo/jobInfoNav""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFPartManageRoleResponse.SFPartManageRole>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            needAdds.Add(new SFPositionUserRelEntity()
                            {
                                Id = Guid.NewGuid().ToString(),
                                DataType = 2,
                                PositionCode = item?.allSfProcesses?.results?.FirstOrDefault()?.usersSysIdNav?.empInfo?.jobInfoNav?.results?.FirstOrDefault()?.position,
                                UserId = string.IsNullOrEmpty(item.externalCode) ? string.Empty : item.externalCode.Split('-')[0]
                            });
                        }
                    }
                }

                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFPositionUserRelEntity>().Where(t => t.DataType == 2).ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncGetPartManagerRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取HRBP,HRBPHead,HRBP主管,CEO ,HRVP等角色
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetHRBPRole()
        {
            string msgResult = "---- SyncGetHRBPRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetHRBPRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFApproverEntity> needAdds = new List<SFApproverEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""externalCode,department,position""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFCommonApproverResponse.SFCommonApprover>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            needAdds.Add(new SFApproverEntity()
                            {
                                Id = Guid.NewGuid().ToString(),
                                DeptCode = item.department,
                                RoleCode = item.externalCode,
                                PositionCode = item.position
                            });
                        }
                    }
                }

                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFApproverEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();

                    var postions = _dbPlatform.Queryable<SFPositionUserRelEntity>().ToList();

                    await AddCommonRoleUser(needAdds.Where(t => t.RoleCode != "HRBPPermission" && !string.IsNullOrEmpty(t.DeptCode)).Select(t => new CommonRoleUserDto()
                    {
                        DeptCode = t.DeptCode,
                        RoleCode = t.RoleCode,
                        RoleName = t.RoleCode,
                        UserCode = postions.FirstOrDefault(s => s.PositionCode == t.PositionCode)?.UserId
                    }).ToList());
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncGetHRBPRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取部门负责人
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetDeptLeaderRole()
        {
            string msgResult = "---- SyncGetDeptLeaderRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetDeptLeaderRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFDeptLeaderEntity> needAdds = new List<SFDeptLeaderEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""startDate,endDate,externalCode,name_zh_CN,status,headOfUnit,cust_DepartmentToDepartmentProp,cust_route,cust_organizationCategory,headOfUnitNav/empInfo/personIdExternal"",""$expand"":""headOfUnitNav/empInfo""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFDepartLeaderResponse.SFDepartLeader>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            if (item.status == "A")
                            {
                                var userid = item.headOfUnit;
                                if (!string.IsNullOrEmpty(item?.headofunitNav?.empInfo?.personIdExternal))
                                {
                                    userid = item?.headofunitNav?.empInfo?.personIdExternal;
                                }

                                needAdds.Add(new SFDeptLeaderEntity()
                                {
                                    Id = Guid.NewGuid().ToString(),
                                    DeptCode = item.externalCode,
                                    DeptName = item.name_zh_CN,
                                    UserId = string.IsNullOrEmpty(userid) ? string.Empty : userid.Split('-')[0],
                                    DeptCategory = item.cust_organizationCategory,
                                    FullPathCode = item.cust_route,
                                    ParentDeptCode = item.cust_DepartmentToDepartmentProp,
                                });
                            }
                        }
                    }
                }

                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFDeptLeaderEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();

                    // 插入二级部门负责人，三级部门负责人
                    var deptcodes = _dbPlatform.Queryable<UserExtension>().Select(t => new { t.Objid_2, t.Objid_3 }).Distinct().ToList();

                    var twodeptcodes = deptcodes.Select(t => t.Objid_2).Distinct().ToList();
                    var threedeptcodes = deptcodes.Select(t => t.Objid_3).Distinct().ToList();
                    await AddCommonRoleUser(needAdds.Where(t => twodeptcodes.Contains(t.DeptCode)).Select(t => new CommonRoleUserDto()
                    {
                        DeptCode = t.DeptCode,
                        RoleName = "二层组织负责人",
                        RoleCode = "SecondLevelHeadOfOrganization",
                        UserCode = t.UserId
                    }).ToList());
                    await AddCommonRoleUser(needAdds.Where(t => threedeptcodes.Contains(t.DeptCode)).Select(t => new CommonRoleUserDto()
                    {
                        DeptCode = t.DeptCode,
                        RoleName = "三层组织负责人",
                        RoleCode = "TertiaryLevelHeadOfOrganization",
                        UserCode = t.UserId
                    }).ToList());
                }
            }
            catch (Exception ex)
            {
                msgResult = "----  SyncGetDeptLeaderRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 同步DOA审批角色和人
        /// </summary>
        /// <param name="syncData">同步数据</param>
        /// <returns>正确</returns>
        private async Task<string> AddCommonRoleUser(List<CommonRoleUserDto> syncData)
        {
            try
            {
                if (syncData == null || syncData.Count() == 0)
                {
                    return string.Empty;
                }

                // 数据处理，有个奇怪的空格，需要替换下
                syncData.ForEach(t =>
                {
                    t.RoleName = t.RoleName.Replace(" ", " ");
                });

                // 第一步，同步角色
                var commonroles = await _dbPlatform.Queryable<CommonRole>().ToListAsync();
                var roleNames = commonroles.Select(t => t.RoleName).ToList();

                var needaddrolenames = syncData.Select(t => t.RoleName).Distinct().ToList();

                // 没有的
                needaddrolenames = needaddrolenames.Except(roleNames).ToList();
                if (needaddrolenames != null && needaddrolenames.Count() > 0)
                {
                    List<CommonRole> roles = new List<CommonRole>();
                    foreach (var item in needaddrolenames)
                    {
                        var commonrole = syncData.FirstOrDefault(t => t.RoleName == item);

                        // 插入角色
                        roles.Add(new CommonRole()
                        {
                            RoleId = Guid.NewGuid(),
                            RoleType = "0",
                            RoleName = item,
                            RoleCode = commonrole.RoleCode,
                            Status = 1,
                            CreateUserId = "e8575564-17e8-4d9a-8ab3-e055c366dc62".ToOurGuid(),
                            CreateDate = DateTime.Now,
                        });
                    }

                    if (roles.Count() > 0)
                    {
                        commonroles.AddRange(roles);
                        _dbPlatform.Insertable(roles).ExecuteCommand();
                    }
                }

                // 插入角色，组织，人的关系
                List<CommonRoleUserRelation> addRelations = new List<CommonRoleUserRelation>();
                List<CommonRoleUserRelation> deleteRelations = new List<CommonRoleUserRelation>();
                var totalUserRelations = _dbPlatform.Queryable<CommonRoleUserRelation>().ToList();
                var users = _dbPlatform.Queryable<Users>().Select(t => new { t.UserId, t.WorkNumber, t.UserName }).ToList();
                // 待删除数据RoleID
                List<Guid> delroleids = new List<Guid>();

                foreach (var item in syncData)
                {
                    var commonrole = commonroles.FirstOrDefault(t => t.RoleName == item.RoleName);
                    if (!delroleids.Contains(commonrole.RoleId))
                    {
                        delroleids.Add(commonrole.RoleId);
                    }

                    var relation = totalUserRelations.Where(t => t.RoleId == commonrole.RoleId && t.OrgCode == item.DeptCode).FirstOrDefault();
                    var user = users.FirstOrDefault(t => t.WorkNumber == item.UserCode);

                    // 新进来的，统统算新增
                    if (user != null)
                    {
                        relation = new CommonRoleUserRelation()
                        {
                            RoleUserRelationId = Guid.NewGuid(),
                            RoleId = commonrole.RoleId,
                            OrgCode = item.DeptCode,
                            CreateDate = DateTime.Now,
                            CreateUserId = "e8575564-17e8-4d9a-8ab3-e055c366dc62".ToOurGuid(),
                            UserId = user.UserId,
                            UserName = user.UserName
                        };
                        addRelations.Add(relation);
                    }
                }

                if (delroleids.Count() > 0)
                {
                    deleteRelations = totalUserRelations.Where(t => delroleids.Contains(t.RoleId ?? Guid.NewGuid())).ToList();
                    _dbPlatform.Deleteable(deleteRelations).ExecuteCommand();
                }

                if (addRelations.Count() > 0)
                {
                    _dbPlatform.Insertable(addRelations).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

            return "true";
        }

        /// <summary>
        /// 获取其他角色
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncGetOtherRole()
        {
            string msgResult = "---- SyncGetOtherRole  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetotherRole_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFOtherApproverEntity> needAdds = new List<SFOtherApproverEntity>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFOtherResponse.SFOther>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        // 数据处理
                        foreach (var item in result?.d?.results)
                        {
                            needAdds.Add(new SFOtherApproverEntity()
                            {
                                Id = Guid.NewGuid().ToString(),
                                RelationshipType = item.relationshipType,
                                RelUserId = item.relUserId,
                                UserId = string.IsNullOrEmpty(item.userId) ? string.Empty : item.userId.Split('-')[0]
                            });
                        }
                    }
                }

                if (needAdds.Count() > 0)
                {
                    _dbPlatform.Deleteable<SFOtherApproverEntity>().ExecuteCommand();
                    _dbPlatform.Insertable(needAdds).ExecuteCommand();
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncGetOtherRole  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取职位附加信息（所属区域）
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncPostionExpand()
        {
            string msgResult = "---- SyncPostionExpand  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetEmpJob_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFUserAreaResponse.SFUserAreaData> needUpdates = new List<SFUserAreaResponse.SFUserAreaData>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""$select"":""startDate,customString22,userId,customString21,customString21Nav/externalName"",""$expand"":""customString21Nav""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFUserAreaResponse.SFUserArea>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.d?.results);
                    }
                }

                if (needUpdates.Count() > 0)
                {
                    var allExpand1User = _dbPlatform.Queryable<UserExtension>().ToList();
                    var allUser = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                    foreach (var user in allUser)
                    {
                        var needUpdate = needUpdates.FirstOrDefault(t => t.userId == user.WorkNumber);
                        if (needUpdate != null)
                        {
                            user.RegionCode = needUpdate.customString21;
                            user.RegionName = needUpdate.customString21Nav?.externalName;
                        }
                    }

                    if (allUser.Count() > 0)
                    {
                        _dbPlatform.Updateable(allUser).UpdateColumns(t => new { t.RegionCode, t.RegionName }).ExecuteCommand();
                    }

                    // 性能问题，在扩展1表里也加下所属区域
                    foreach (var expand in allExpand1User)
                    {
                        var needUpdate = needUpdates.FirstOrDefault(t => t.userId == expand.Sapemployeeid);
                        if (needUpdate != null)
                        {
                            expand.RegionCode = needUpdate.customString21;
                            expand.RegionName = needUpdate.customString21Nav?.externalName;
                        }
                    }

                    if (allExpand1User.Count() > 0)
                    {
                        _dbPlatform.Updateable(allExpand1User).UpdateColumns(t => new { t.RegionCode, t.RegionName }).ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncPostionExpand  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 获取考勤附加信息接口说明文档(工时属性)
        /// </summary>
        /// <returns></returns>
        private async Task<string> SyncUserTimeSheet()
        {
            string msgResult = "---- SyncPostionExpand  Success  ---------";
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>()
                {
                    { "serviceName", "S_XXX_SF_GetCustworktime_S" },
                    { "sourceSystem", string.IsNullOrEmpty(_sourceSystem) ? "BPMNEW" : _sourceSystem }
                };

                int count = 1000;
                int skip = 0;
                List<SFUserTimeSheetResponse.SFUserTimeSheetData> needUpdates = new List<SFUserTimeSheetResponse.SFUserTimeSheetData>();
                while (count == 1000)
                {
                    // 总是挂，间隔2s再请求
                    await Task.Delay(2000);
                    var requestBody = @"{""$top"":" + count + @",""$skip"":" + skip + @",""$format"":""json"",""fromDate"":""1990-01-01"",""$select"":""effectiveStartDate,externalCode,externalName,cust_attribute,mdfSystemEffectiveEndDate""}";
                    var result = await _nPRestHttp.ESBPostAsync<SFUserTimeSheetResponse.SFUserTimeSheet>(_esbSFGetUrl, requestBody, dic);
                    count = result?.d?.results?.Count() ?? 0;
                    skip = skip + 1000;
                    if (count > 0)
                    {
                        needUpdates.AddRange(result?.d?.results);
                    }
                }

                if (needUpdates.Count() > 0)
                {
                    var allUser = _dbPlatform.Queryable<UserExtensionSecondEntity>().ToList();
                    var startDate = DateTime.Now;
                    var endDate = DateTime.Now;
                    var now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 12, 0, 0);
                    foreach (var user in allUser)
                    {
                        var needUpdate = needUpdates.Where(t => t.externalCode == user.WorkNumber).ToList();
                        if (needUpdate != null)
                        {
                            foreach (var item in needUpdate)
                            {
                                if (!item.effectiveStartDate.IsNullOrEmpty() && !item.mdfSystemEffectiveEndDate.IsNullOrEmpty())
                                {
                                    startDate = ToSFDateTime(item.effectiveStartDate).Value;
                                    endDate = ToSFDateTime(item.mdfSystemEffectiveEndDate).Value;

                                    if (startDate <= now && endDate >= now)
                                    {
                                        // 0—标准工时；1—不定时工时；2—综合计算工时；3—无
                                        user.TimeSheetType = item.externalName == "0" ? "标准工时"
                                            : item.externalName == "1" ? "不定时工时"
                                            : item.externalName == "2" ? "综合计算工时"
                                            : item.externalName == "3" ? "无" : String.Empty;
                                    }
                                }
                            }
                        }
                    }

                    if (allUser.Count() > 0)
                    {
                        _dbPlatform.Updateable(allUser).UpdateColumns(t => t.TimeSheetType).ExecuteCommand();
                    }
                }
            }
            catch (Exception ex)
            {
                msgResult = "---- SyncPostionExpand  Failed  ---------" + ex.Message;
            }

            return msgResult;
        }

        /// <summary>
        /// 将日期转成SF需要的str
        /// 注意，推送给SF的数据，日期要加8H
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public string ToSFStr(DateTime date, bool IsPush = false)
        {
            if (date == null)
            {
                return "0";
            }

            if (IsPush)
            {
                date = date.AddHours(8);
            }

            DateTimeOffset dateTime = new DateTimeOffset(date);
            return string.Format("/Date({0})/", dateTime.ToUnixTimeMilliseconds());
        }

        /// <summary>
        /// 将SF日期转成DateTime
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public DateTime? ToSFDateTime(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }

            long millSeconds = 0;
            str = str.Replace("/Date(", string.Empty).Replace(")/", string.Empty);
            bool isTrue = long.TryParse(str, out millSeconds);
            if (isTrue)
            {
                if (str.Length >= 13)
                {
                    return DateTimeOffset.FromUnixTimeMilliseconds(millSeconds).ToLocalTime().DateTime;
                }
                else if (str.Length == 10)
                {
                    return DateTimeOffset.FromUnixTimeSeconds(millSeconds).ToLocalTime().DateTime;
                }

                return null;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 电子签相关
        /// <summary>
        /// 文件下载URL获取
        /// </summary>
        /// <param name="flowid">流程号</param>
        /// <returns></returns>
        private string GetESDownloadUrl(string flowid)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(flowid))
            {
                return result;
            }
            try
            {
                string url = string.Concat(_eSignUrl, "/V1/signFlows/getSignFlowDocUrls" + "?intranetFlag=N&signFlowId=", flowid);
                var requestBody = new
                {
                    signFlowId = flowid,
                    intranetFlag = "N"
                };
                var eSResultData = this.GetAsync<ESDto.ESCommonResponseForOne>(url, AddESHeader()).Result;

                if (eSResultData.ErrCode == 0 && eSResultData.Data != null)
                {
                    var data = JsonConvert.DeserializeObject<ESDto.ESFileResponse>(eSResultData.Data.ToString());
                    if (data != null && data.SignDocUrlList != null && data.SignDocUrlList.Count() > 0)
                    {
                        result = data.SignDocUrlList[0].DownloadDocUrl;
                    }
                }
            }
            catch (Exception)
            {
            }
            return result;
        }

        /// <summary>
        /// Base64 SHA256
        /// </summary>
        /// <param name="data">待加密数据</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        private static string SHA256Encrypt(string data, string secret)
        {
            secret = secret ?? string.Empty;
            var encoding = Encoding.UTF8;
            byte[] keyByte = encoding.GetBytes(secret);
            byte[] dataBytes = encoding.GetBytes(data);
            using (var hmac256 = new HMACSHA256(keyByte))
            {
                byte[] hashData = hmac256.ComputeHash(dataBytes);
                return BitConverter.ToString(hashData, 0).Replace("-", string.Empty).ToLower();
                //return Convert.ToBase64String(hashData);
            }
        }

        private Dictionary<string, string> AddESHeader(Dictionary<string, string> valuePairs = null, string contentType = "application/json")
        {
            if (valuePairs == null)
            {
                valuePairs = new Dictionary<string, string>();
            }

            if (!valuePairs.ContainsKey("x-timevale-project-id"))
            {
                valuePairs.Add("x-timevale-project-id", _projectKey);
            }

            if (!valuePairs.ContainsKey("x-timevale-signature"))
            {
                valuePairs.Add("x-timevale-signature", _signature);
            }

            if (!valuePairs.ContainsKey("Content-Type") && !contentType.IsNullOrEmpty())
            {
                valuePairs.Add("Content-Type", contentType);
            }

            return valuePairs;
        }

        /// <summary>
        /// 重写Get方法，提供header参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        private async Task<T> GetAsync<T>(string url, Dictionary<string, string> headers = null)
        {
            RestClient client = new RestClient(url);
            RestRequest request = new RestRequest("", Method.GET);
            if (headers != null && headers.Count > 0)
            {
                request.AddOrUpdateHeaders(headers);
            }

            IRestResponse response = await client.ExecuteAsync(request);
            string content = "";
            if (response != null && response.Content != null)
            {
                content = response.Content;
            }
            return (T)(string.IsNullOrEmpty(content) ? ((object)default(T)) : ((object)JsonConvert.DeserializeObject<T>(content))); ;
        }

        #endregion
    }
}
